// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Helper library to convert simple object to DOM nodes.
 * This code designed to be compiled using the Closure Compiler.
 * @author j.s@google.com (Jeff Scudder)
 */
(function() {
  function element(opt_tag, opt_attrib, opt_nodes) {
    return {'tag': opt_tag || '', 'attrib': opt_attrib || {},
            'nodes': opt_nodes || []};
  }

  function text(opt_text) {
    return {'text': opt_text || null};
  }

  function toDom(item) {
    // Create shortenable aliases for public class properties.
    var tag = item['tag'];
    var attrib = item['attrib'];
    var nodes = item['nodes'];
    var text = item['text'];

    if (text && text != null) {
      return document.createTextNode(text);
    }

    if (!tag) {
      return null;
    }

    var dom = document.createElement(tag);

    for (var key in attrib) {
      // Only convert actual properties of this object, ignore those added by
      // frameworks.
      if (attrib.hasOwnProperty(key)) {
        // The style attribute gets special treatment since it is structured
        // as a nested object.
        if (key == 'style') {
          for (var style in attrib[key]) {
            if (attrib[key].hasOwnProperty(style)) {
              dom[key][style] = attrib[key][style];
            }
          }
        } else {
          dom[key] = attrib[key];
        }
      }
    }

    for (var i = 0; i < nodes.length; i++) {
      var child = toDom(nodes[i]);
      if (child != null) {
        dom.appendChild(child);
      }
    }

    return dom;
  }

  window['obj2dom'] = window['obj2dom'] || {};
  window['obj2dom']['element'] = element;
  window['obj2dom']['text'] = text;
  window['obj2dom']['toDom'] = toDom;
})();
